import { ref, nextTick } from 'vue'
import app from '@/app'
import configStore from '@/plugin/config/store'
import taxStore from '@/plugin/config/store/tax'
import clientStore from '@/plugin/client/store'
import orderStore from '../../store'
import expectStore from '../../store/expect'
import index from '../../index'

const store = {
  type: ref(),
  ok: ref(false),
  i: 0,
  data: ref({}),
  goods: ref([]),
  discount: ref(0),

  getData() {
    return this.data.value
  },

  getGoods() {
    return this.goods.value
  },

  async enter(data) {
    app.router.push('/plugin/order/create')
    await this.init(data, data.goods ?? [])
  },

  async enterOrder(data = {}, retreat = false) {
    this.type.value = 'order'
    if(retreat) {
      data = this.enterRetreat(Object.assign({}, data))
    }
    // 永远都是新发票
    await this.enter(this.enterCreate(data))
  },

  async enterExpect(data = {}, create = false) {
    this.type.value = 'expect'
    await this.enter(create ? this.enterCreate(data) : data)
  },

  // 创建模式
  enterCreate(data) {
    data.id = null
    data.code = null

    return data
  },

  // 进入退款
  enterRetreat(data) {
    // 将改为退款发票
    data.ticket = data.ticket.includes('_refund') ? data.ticket : (data.ticket  + '_refund')
    // 并将原code记录下
    data.code_key = data.code
    // 商品数量全部反转
    data.goods.forEach(item => {
      item.count *= -1
    })

    return data
  },

  async init(data = {}, goods = []) {
    // 加载配置
    this.ok.value = false
    await configStore.get()
    await taxStore.get()
    this.ok.value = true

    this.initData(data, goods)
  },

  initData(data = {}, goods = []) {
    // 重置表单
    this.data.value = Object.assign({
      client_data: {},
      ticket: 'ticket',
      count: 0,
      money: 0,
      money_tax: 0,
      total: 0,
      discount_money: 0,
      tax_list: [],
      tax_money: 0,
      req_list: [],
      req_money: 0,
      cost_money: 0,
      profit_money: 0,
      code_key: '',
      remarks: '',
      goods: []
    }, data)

    // 商品信息
    this.goods.value = goods
    // 客户信息
    this.client(this.getData().client_data)
    // 发票时间
    this.getData().status_time = this.getData().status_time ? app.time.load(this.getData().status_time).toDate() : null
  },

  // 生成商品信息
  make(goods = {}) {
    return {
      id          : this.getGoods().length,
      goods_id    : goods.id ?? 0,
      goods_name  : goods.name ?? '',
      goods_number: goods.number ?? '',
      goods_code  : goods.code ?? '',
      goods_image : goods.image ?? '',
      goods_data  : {
        sname         : goods.sname ?? '',
        price         : Number(goods.price ?? 0),
        price_discount: 0,
        price_cost    : Number(goods.price_cost ?? 0),
        unit          : goods.unit ?? '',
        unit_count    : Number(goods.unit_count ?? ''),
        req           : taxStore.req(goods.tax_id ?? taxStore.default()),
        tax           : taxStore.tax(goods.tax_id ?? taxStore.default()),
        law           : taxStore.law(goods.tax_id ?? taxStore.default()),
        tax_name      : taxStore.getName(goods.tax_id ?? taxStore.default()),
        append        : goods.append
      },
      price       : Number(goods.price ?? 0),
      discount    : 0,
      count       : 1,
      total       : 0
    }
  },

  // 更新统计
  update() {
    // 统计字段
    let count = 0, 
    money = 0, 
    money_tax = 0, 
    total = 0, 
    discount_money = 0,
    tax_money = 0, 
    req_money = 0,
    cost_money = 0

    // 税列表
    const tax = []

    // 循环商品
    this.getGoods().forEach(goods => {
      // 商品价格
      goods.total = app.math.mul(goods.price, goods.count)
      // 商品成本
      goods.cost_money = app.math.mul(goods.goods_data.price_cost, goods.count)

      // 税模式
      this.clientTax(goods)
      
      // 商品价格模式
      if(configStore.taxType()) {
        goods.price_tax = app.math.factory(goods.price).divpro(goods.tax).format()
        goods.money_tax = app.math.factory(goods.price).divpro(goods.tax).mul(goods.count).format()
        goods.price_after = goods.price
        goods.money = app.math.mul(goods.price, goods.count)
      } else {
        goods.price_tax = goods.price
        goods.money_tax = app.math.mul(goods.price, goods.count)
        goods.price_after = app.math.factory(goods.price).addpro(goods.tax).format()
        goods.money = app.math.factory(goods.price).addpro(goods.tax).mul(goods.count).format()
      }

      // 总和
      goods.money = app.math.mul(goods.price_after, goods.count)
      

      // 存在优惠金额
      if(Number(goods.discount)) {
        // 优惠比例换算金额
        goods.discount_money = app.math.pro(goods.money_tax, goods.discount)
        // 税前总和减去
        goods.money_tax = app.math.subpro(goods.money_tax, goods.discount)
        // 推算税后总和
        goods.money = app.math.addpro(goods.money_tax, goods.tax)
      } else {
        goods.discount_money = 0
      }

      // 算出税额
      goods.tax_money = app.math.sub(goods.money, goods.money_tax)

      // 判断个体税
      if(Number(goods.req)) {
        // 个体税额
        goods.req_money = app.math.pro(goods.money_tax, goods.req)
        // 加入到税后
        goods.money = app.math.add(goods.money, goods.req_money)
      } else {
        goods.req_money = 0
      }

      goods.profit_money = app.math.sub(goods.money_tax, goods.cost_money)
      
      // 总统计
      count          = app.math.add(count, goods.count)
      money          = app.math.add(money, goods.money)
      money_tax      = app.math.add(money_tax, goods.money_tax)
      total          = app.math.add(total, goods.total)
      tax_money      = app.math.add(tax_money, goods.tax_money)
      req_money      = app.math.add(req_money, goods.req_money)
      cost_money     = app.math.add(cost_money, goods.cost_money)
      discount_money = app.math.add(discount_money, goods.discount_money)

      // 加入税
      let tax_item = tax.find(list => list.key == Number(goods.tax) + '-' + Number(goods.req))
      if(!tax_item) {
        tax_item = tax[tax.push({
          key: goods.tax + '-' + goods.req,
          tax: goods.tax,
          req: goods.req,
          money_tax: 0,
          tax_money: 0, 
          req_money: 0,
          total: 0
        }) - 1]
      }

      tax_item.money_tax = app.math.add(tax_item.money_tax, goods.money_tax)
      tax_item.tax_money = app.math.add(tax_item.tax_money, goods.tax_money)
      tax_item.req_money = app.math.add(tax_item.req_money, goods.req_money)
      tax_item.total = app.math.add(tax_item.total, goods.money)
    })

    // 保存总价和总数量
    this.getData().count          = count
    this.getData().money          = money
    this.getData().money_tax      = money_tax
    this.getData().total          = total
    this.getData().discount_money = discount_money
    this.getData().tax            = tax
    this.getData().tax_money      = tax_money
    this.getData().req_money      = req_money
    this.getData().cost_money     = cost_money
    this.getData().profit_money   = app.math.sub(money_tax, cost_money)

    console.log(this.getData(), this.getGoods())
  },

  // 更新税率
  tax(data) {
    this.getGoods()[this.i].goods_data.tax = taxStore.tax(data.id)
    this.getGoods()[this.i].goods_data.req = taxStore.req(data.id)
    this.getGoods()[this.i].goods_data.law = taxStore.law(data.id)
    this.getGoods()[this.i].goods_data.tax_name = taxStore.getName(data.id)
    
    this.update()
  },

  // 载入客户
  client(data) {
    this.getData().client_data = data ?? {}
    this.getData().client_id = data ? data.id : 0
    this.getData().client_name = data ? data.name : ''

    // 客户批量折扣
    this.getData().order_discount = Number(Math.max(configStore.orderDiscount(), data.classify ? data.classify.discount : 0))

    this.update()
  },

  // 客户税率
  clientTax(goods) {
    // 如果存在
    const tax_id = this.getData().client_data.classify?.tax_id
    // 判断是否为附加商品
    if(tax_id > 0 && !goods.goods_data.append) {
      goods.tax = taxStore.tax(tax_id)
      goods.req = taxStore.req(tax_id)
      goods.law = taxStore.law(tax_id)
      goods.tax_name = taxStore.getName(tax_id)
    } else {
      goods.tax = goods.goods_data.tax
      goods.req = goods.goods_data.req
      goods.law = goods.goods_data.law
      goods.tax_name = goods.goods_data.tax_name
    }

    // 客户不是个体，不需要个体税
    if(!this.clientType()) {
      goods.req = 0
    }
  },

  // 获取客户是否个体
  clientType() {
    return clientStore.type(this.getData().client_data)
  },

  // 批量折扣
  orderDiscount() {
    // 循环商品
    this.getGoods().forEach(goods => {
      if(!goods.goods_data.append) {
        goods.discount = Number(this.getData().order_discount)
      }
    })
    
    this.update()
  },

  // 指针
  index(i) {
    this.i = i
  },

  // 新增栏
  add(goods = {}) {
    const i = this.getGoods().push(this.make(goods))
    this.update()

    return i
  },

  // 填充
  put(goods) {
    this.getGoods()[this.i] = this.make(goods)
    
    this.update()
  },

  // 删除
  del(index) {
    this.getGoods().splice(index, 1)

    this.update()
  },

  // 复制
  async copy(index) {
    const goods = JSON.parse(JSON.stringify(this.getGoods()[index]))
    // 重置ID
    this.getGoods().push({ ...goods, id: this.getGoods().length })

    this.update()
  },

  // 检查数据
  valid() {
    if(!this.getData().ticket.includes('print')) {
      if(!this.getData().client_id) {
        return app.message('warning', index.plugin.message('message.client'))
      }
    } else {
      // 检查发票类型
      if(!configStore.printNorm(this.getData().money)) {
        return app.message('warning', index.plugin.message('message.print_norm'))
      }
    }

    if(!this.getGoods().length) {
      return app.message('warning', index.plugin.message('message.goods'))
    }

    return true
  },

  // 提交
  async postTicket(back = true) {
    // 组合数据
    const data = Object.assign({}, this.getData())
    data.goods = this.getGoods()

    // 提交订单
    const order = await orderStore.update(data)

    // 生成Code
    const code = await configStore.code(data.ticket)

    // 拿到id锁定
    await orderStore.status(order.data.id, code, data.status_time ? app.time.load(data.status_time).unix() : null)

    if(back) {
      // 后退
      app.router.back()
      return code
    } else {
      return { code, id: order.data.id }
    }
  },

  // 提交预算
  async postExpect() {
    // 组合数据
    const data = Object.assign({}, this.getData())
    data.goods = this.getGoods()
    data.status_time = data.status_time ? app.time.load(data.status_time).unix() : null

    if(!data.id) {
      data.code = await configStore.code('expect')
    }

    // 提交订单
    await expectStore.update(data)

    // 后退
    app.router.back()

    return data.code
  }
}

export default store